<template>
  <div class="mainpg">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>采购分组</span>
          </div>
        </div>
      </div>
    </div>
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10 paddingTop0">
        <div class="main_ti">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="已绑定" name="1"></el-tab-pane>
            <el-tab-pane label="未绑定" name="2"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="mainor_form batch-wrap form-item-mg">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
          >
            <el-form-item label="用户名称：" prop="nickname">
              <el-input
                v-model.trim="form.nickname"
                placeholder="用户名称"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="分组：" prop="group_id">
              <el-select
                v-model.trim="form.group_id"
                placeholder="分组"
                class="wid220"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(group, index) in list.group"
                  :key="index"
                  :label="group"
                  :value="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区域：" prop="region_id">
              <el-select
                v-model.trim="form.region_id"
                placeholder="区域"
                class="wid220"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(region, index) in list.region"
                  :key="index"
                  :label="region"
                  :value="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button @click="tying(false)" v-if="activeName == 1" v-repeatClick>批量解绑</el-button>
              <el-button @click="batch(false)" v-if="activeName == 2" v-repeatClick>批量绑定</el-button>
            </MainFormBtn>
          </el-form>
        </div>
        <div
          class="main_table marginTop0"
          style="min-height: 670px"
          v-if="activeName == 1"
        >
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="120" />
            <el-table-column
              label="用户名称"
              prop="nickname"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机"
              prop="mobile"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="200"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link type="success" @click="(e)=>{tying(e,true,scope.$index)}" v-repeatClick
                  >解绑</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div
          class="main_table marginTop0"
          style="min-height: 670px"
          v-if="activeName == 2"
        >
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="120" />
            <el-table-column
              label="用户名称"
              prop="nickname"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机"
              prop="mobile"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="200"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link type="success" @click="(e)=>{batch(e,true,scope.$index)}" v-repeatClick
                  >绑定</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  purchaseGroup_bindUsers,
  purchaseGroup_unbindUsers,
  purchaseGroup_bind,
  purchaseGroup_unbind,
} from "@/api/purchasing/purchasingGroup";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  components: {},
  data() {
    return {
      // 全选
      selectArr: [],
      // 选中菜单
      activeName: "1",
      // 搜索
      form: {
        nickname: "",
        group_id: null,
        region_id: null,
      },
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      listLoading: false,
      // id
      id: this.$route.params.id,
    };
  },
  created() {
    // 列表
    this.purchaseGroup_bindUsers();
  },
  methods: {
    reset() {
      this.$refs['userListFrom'].resetFields()
      this.purchaseGroup_bindUsers();
    },
    // 选中菜单
    handleClick(tab, event) {
      this.form = {
        name: "",
        group_id: null,
        region_id: null,
      };
      this.current = {
        page: 1,
        per_page: 20,
      };
      this.limit = 20;
      this.$refs["userListFrom"].clearValidate();
      if (tab.name == 1) {
        this.purchaseGroup_bindUsers();
      } else {
        this.purchaseGroup_unbindUsers();
      }
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
    // 解绑
    tying(e,type,index) {
      if (!type) {
        if (this.selectArr.length != 0) {
          this.$confirm("确定批量解绑?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.purchaseGroup(false);
            })
            .catch(() => {});
        } else {
          this.$message.error("请勾选用户");
        }
        return
      }
      if (e.path[1].disabled) {
        return
      }
      this.purchaseGroup(true,index);
    },
    // 绑定
    batch(e,type,index) {
      if (!type) {
        if (this.selectArr.length != 0) {
          this.$confirm("确定批量绑定?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.purchaseGroup(false);
            })
            .catch(() => {});
        } else {
          this.$message.error("请勾选用户");
        }
        return;
      }
      if (e.path[1].disabled) {
        return
      }
      this.purchaseGroup(true,index);
    },
    purchaseGroup(type,index) {
      let ids = type
        ? JSON.stringify([{ id: this.list.list.data[index].id }])
        : JSON.stringify(this.selectArr);
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                ids: ids,
                id: this.id,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: ids, id: this.id }
      );
      if (this.activeName == 1) {
        purchaseGroup_unbind(data).then((res) => {
          this.listLoading = false;
          if (res.errcode == 0) {
            this.$message({
              message: "解绑成功",
              type: "success",
            });
            if(type){
              this.list.list.data.splice(index, 1);
            }else{
              this.$refs.multipleTable.clearSelection();
              this.purchaseGroup_bindUsers();
            }
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
        purchaseGroup_bind(data).then((res) => {
          this.listLoading = false;
          if (res.errcode == 0) {
            this.$message({
              message: "绑定成功",
              type: "success",
            });
            if(type){
              this.list.list.data.splice(index, 1);
            }else{
              this.$refs.multipleTable.clearSelection();
              this.purchaseGroup_unbindUsers();
            }
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      if (this.activeName == 1) {
        this.purchaseGroup_bindUsers();
      } else {
        this.purchaseGroup_unbindUsers();
      }
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      if (this.activeName == 1) {
        this.purchaseGroup_bindUsers();
      } else {
        this.purchaseGroup_unbindUsers();
      }
    },
    changePage(page) {
      this.current.page = page;
      if (this.activeName == 1) {
        this.purchaseGroup_bindUsers();
      } else {
        this.purchaseGroup_unbindUsers();
      }
    },
    // 列表
    purchaseGroup_bindUsers() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.current,
        { id: this.id },
        JSON.parse(JSON.stringify(this.form))
      );
      purchaseGroup_bindUsers(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    purchaseGroup_unbindUsers() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.current,
        { id: this.id },
        JSON.parse(JSON.stringify(this.form))
      );
      purchaseGroup_unbindUsers(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 300px);
}
.main_crumbs {
  border-bottom: 0;
}
/deep/.el-tabs__header {
  margin: 0 0 11px;
}
</style>
